from flask_restful import Resource, reqparse
from flask import request
from models import db, Note
from utils import api_response
import logging

# 配置日志
logger = logging.getLogger(__name__)

class NoteList(Resource):
    def get(self):
        """获取便签列表"""
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('user_id', type=int, location='args')
            parser.add_argument('page', type=int, default=1, location='args')
            parser.add_argument('size', type=int, default=10, location='args')
            args = parser.parse_args()
            
            query = Note.query
            if args['user_id'] is not None:
                query = query.filter_by(user_id=args['user_id'])
            
            notes = query.paginate(
                page=args['page'], 
                per_page=args['size'], 
                error_out=False
            )
            
            return api_response({
                'total': notes.total,
                'page': args['page'],
                'size': args['size'],
                'notes': [note.to_dict() for note in notes.items]
            })
        except Exception as e:
            logger.error(f"Error in NoteList.get: {str(e)}")
            import traceback
            logger.error(f"Traceback: {traceback.format_exc()}")
            return api_response(None, f"获取便签列表失败: {str(e)}", 500)
    
    def post(self):
        """创建便签"""
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('user_id', type=int, required=True, help='用户ID不能为空')
            parser.add_argument('type', type=str, required=True, help='便签类型不能为空')
            parser.add_argument('title', type=str, required=True, help='便签标题不能为空')
            parser.add_argument('content', type=str, required=True, help='便签内容不能为空')
            parser.add_argument('tag', type=str, help='便签分类不能为空')
            parser.add_argument('priority', type=str, help='便签优先级')
            args = parser.parse_args()
            
            note = Note(
                user_id=args['user_id'],
                type=args['type'],
                title=args['title'],
                content=args['content'],
                tag=args['tag'],
                priority=args['priority']
            )
            
            db.session.add(note)
            db.session.commit()
            
            return api_response(note.to_dict(), message='便签创建成功')
        except Exception as e:
            logger.error(f"Error in NoteList.post: {str(e)}")
            db.session.rollback()
            return api_response(None, f"创建便签失败: {str(e)}", 500)

class NoteDetail(Resource):
    def get(self, note_id):
        """获取便签详情"""
        try:
            note = Note.query.get(note_id)
            if not note:
                return api_response({'message': '便签不存在'}, code=404)
            
            return api_response(note.to_dict())
        except Exception as e:
            logger.error(f"Error in NoteDetail.get: {str(e)}")
            return api_response(None, f"获取便签详情失败: {str(e)}", 500)
    
    def put(self, note_id):
        """更新便签"""
        try:
            note = Note.query.get(note_id)
            if not note:
                return api_response({'message': '便签不存在'}, code=404)
            
            parser = reqparse.RequestParser()
            parser.add_argument('tag', type=str)
            parser.add_argument('type', type=str)
            parser.add_argument('title', type=str)
            parser.add_argument('content', type=str)
            parser.add_argument('priority', type=str)
            args = parser.parse_args()
            
            if args['tag'] is not None:
                note.tag = args['tag']
            if args['type'] is not None:
                note.type = args['type']
            if args['title'] is not None:
                note.title = args['title']
            if args['content'] is not None:
                note.content = args['content']
            if args['priority'] is not None:
                note.priority = args['priority']
            
            db.session.commit()
            
            return api_response(note.to_dict(), message='便签更新成功')
        except Exception as e:
            logger.error(f"Error in NoteDetail.put: {str(e)}")
            db.session.rollback()
            return api_response(None, f"更新便签失败: {str(e)}", 500)
    
    def delete(self, note_id):
        """删除便签"""
        try:
            note = Note.query.get(note_id)
            if not note:
                return api_response({'message': '便签不存在'}, code=404)
            
            db.session.delete(note)
            db.session.commit()
            
            return api_response(None, message='便签删除成功')
        except Exception as e:
            logger.error(f"Error in NoteDetail.delete: {str(e)}")
            db.session.rollback()
            return api_response(None, f"删除便签失败: {str(e)}", 500)